package com.klun.aop.CGlib;

import com.klun.aop.method.MonitorSession;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 单例
 */
public class CGLibProxy implements MethodInterceptor {

    private static CGLibProxy instance = new CGLibProxy();

    private CGLibProxy() {} // 私有化构造器

    public static CGLibProxy getInstance() {
        return instance;
    }

    private Enhancer enhancer = new Enhancer(); // CGlib包 用来解析字节码的

    @SuppressWarnings("unchecked")
    public  <T> T getProxy(Class<T> clazz) {
        enhancer.setSuperclass(clazz); // 动态创建一个父类
        enhancer.setCallback(this); // 设置？？？
        return (T) enhancer.create(); // 创建
    }
    /**
     * cglib拦截
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects,
                            MethodProxy methodProxy) throws Throwable {
        System.out.println("调用intercept环绕方法******方法名("+method.getName()+")");
        MonitorSession.begin(method.getName()); // 启动
        Object obj = methodProxy.invokeSuper(o, objects); // 构造实体类
        MonitorSession.end(); // 结束
        return obj;
    }
}
